package com.masonluo.mlonlinejudge.service.impl;

import com.alibaba.fastjson.JSON;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.Session;
import com.masonluo.mlonlinejudge.model.dto.TestCaseUploadDto;
import com.masonluo.mlonlinejudge.service.TestcaseFileService;
import com.masonluo.mlonlinejudge.utils.SFTP;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Vector;

import static com.masonluo.mlonlinejudge.utils.SFTP.disConn;
import static com.masonluo.mlonlinejudge.utils.SFTP.getConnect;

@Service
public class TestcaseFileServiceImpl implements TestcaseFileService {
    @Override
    public TestCaseUploadDto sendMultipartFile(MultipartFile file) throws IOException {
        TestCaseUploadDto dto = null;
        String fileName = file.getOriginalFilename();
        //转换成文件流
        InputStream fileInputStream = file.getInputStream();
        //接收文件的服务器地址
        // String uploadURL = "http://119.23.104.65:8099/file";
        // TODO 修改IP地址
        String uploadURL = "http://106.53.210.134:8099/file";
//        String uploadURL = "http://127.0.0.1:8099/file";
        //创建HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(uploadURL);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        //绑定文件参数，传入文件流和ContentType，此处也可以继续添加其他FORM_DATA参数
        builder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);
        //执行提交
        HttpResponse response = httpClient.execute(httpPost);
        //获得文件存储端服务器响应信息
        HttpEntity responseEntity = response.getEntity();
        if (responseEntity != null) {
            //将响应的内容转换成字符串
            String result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            //将Json格式的字符串转换为TestCaseUploadDto对象
            dto = JSON.parseObject(result, TestCaseUploadDto.class);
        }
        //关闭流
        if (fileInputStream != null) {
            fileInputStream.close();
        }
        //关闭流
        httpClient.close();
        return dto;
    }

    @Override
    public void downloadTestCase(String testCaseId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //下载文件的服务器地址
        // String downloadURL = "http://119.23.104.65:8099/downloadAllAttachment";
        // TODO 修改IP地址
        String downloadURL = "http://106.53.210.134:8099/downloadAllAttachment";
//        String downloadURL = "http://127.0.0.1:8099/downloadAllAttachment";

        //创建HttpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(downloadURL);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        //绑定参数
        builder.addTextBody("testCaseId", testCaseId);
        HttpEntity entity = builder.build();
        httpPost.setEntity(entity);

        //执行提交
        httpClient.execute(httpPost);

        //获取服务器临时目录下的zip文件
        // String filePath = "http://119.23.104.65:8099/getUrlDownload";
        // TODO 修改IP地址
        String filePath = "http://106.53.210.134:8099/getUrlDownload";
//        String filePath = "http://127.0.0.1:8099/getUrlDownload";
        URL url = new URL(filePath) ;
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection() ;
        urlConnection.connect() ;
        OutputStream outputStream = response.getOutputStream();
        InputStream inputStream = urlConnection.getInputStream() ;
        IOUtils.copy(inputStream,outputStream);
        inputStream.close();
        response.flushBuffer();
        outputStream.close();

    }

    @Override
    public void deleteTestCase(String testCaseId) throws Exception {
        // TODO 修改测试文件的存放路径
        // String directory = "/home/OnlineJudgeDeploy/data/backend/test_case/" + testCaseId;
        String directory = "/usr/local/mloj/OnlineJudgeDeploy/data/backend/test_case/" + testCaseId;
        SFTP s=new SFTP();
        getConnect(s);//建立连接
        Session session = s.getSession();
        Channel channel = s.getChannel();
        ChannelSftp sftp = s.getSftp();// sftp操作类
        Vector<ChannelSftp.LsEntry> directoryEntries = sftp.ls(directory);
        try {
            for (ChannelSftp.LsEntry file : directoryEntries) {
                if(!String.format(file.getFilename()).equals(".") && !String.format(file.getFilename()).equals("..") ){
                    sftp.cd(directory);
                    sftp.rm(file.getFilename());
                }
            }
            sftp.rmdir(directory);
        } catch (Exception e) {
            throw new Exception(e.getMessage(),e);
        } finally {
            disConn(session,channel,sftp);
        }
    }
}
